"use client";

import { useEffect, useRef, useState } from "react";
import mermaid from "mermaid";
import CodeViewer from "./code-viewer";
import DirectoryViewer from "./directory-viewer";
import { Dialog, DialogContent, DialogTitle } from "./ui/dialog";
// Remove the direct import
// import svgPanZoom from "svg-pan-zoom";

interface MermaidChartProps {
  chart: string;
  zoomingEnabled?: boolean;
  repoUrl?: string;
}

const MermaidChart = ({ chart, zoomingEnabled = true, repoUrl }: MermaidChartProps) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [renderError, setRenderError] = useState<string | null>(null);
  const [selectedFileUrl, setSelectedFileUrl] = useState<string | null>(null);
  const [selectedDirUrl, setSelectedDirUrl] = useState<string | null>(null);
  const [isCodeViewerOpen, setIsCodeViewerOpen] = useState<boolean>(false);
  const [isDirViewerOpen, setIsDirViewerOpen] = useState<boolean>(false);

  useEffect(() => {
    // 重置错误状态
    setRenderError(null);

    // 打印 Mermaid 图表代码到控制台，便于排查语法错误
    console.log("======= Mermaid Diagram Code =======");
    console.log(chart);
    console.log("===================================");

    try {
      // 尝试验证 Mermaid 语法
      mermaid.parse(chart);
      console.log("Mermaid syntax validation: PASSED ✅");

      mermaid.initialize({
        startOnLoad: true,
        theme: "neutral",
        htmlLabels: true,
        flowchart: {
          htmlLabels: true,
          curve: "basis",
          nodeSpacing: 50,
          rankSpacing: 50,
          padding: 15,
        },
        securityLevel: 'loose', // 允许点击事件
        themeCSS: `
          .clickable {
            transition: transform 0.2s ease;
          }
          .clickable:hover {
            transform: scale(1.05);
            cursor: pointer;
          }
          .clickable:hover > * {
            filter: brightness(0.85);
          }
        `,
      });

      const initializePanZoom = async () => {
        const svgElement = containerRef.current?.querySelector("svg");
        if (svgElement && zoomingEnabled) {
          // 移除任何限制性样式
          svgElement.style.maxWidth = "none";
          svgElement.style.width = "100%";
          svgElement.style.height = "auto";
          svgElement.style.minHeight = "400px";
          
          // 调整SVG视口，确保全部内容可见
          const viewBox = svgElement.getAttribute("viewBox");
          if (!viewBox) {
            const bbox = svgElement.getBBox();
            svgElement.setAttribute("viewBox", `0 0 ${bbox.width} ${bbox.height}`);
          }

          if (zoomingEnabled) {
            try {
              // Dynamically import svg-pan-zoom only when needed in the browser
              const svgPanZoom = (await import("svg-pan-zoom")).default;
              // eslint-disable-next-line @typescript-eslint/no-unsafe-call
              svgPanZoom(svgElement, {
                zoomEnabled: true,
                controlIconsEnabled: true,
                fit: true,
                center: true,
                minZoom: 0.1,
                maxZoom: 10,
                zoomScaleSensitivity: 0.3,
              });
            } catch (error) {
              console.error("Failed to load svg-pan-zoom:", error);
            }
          }
        }
      };

      // 从Mermaid代码中提取点击信息
      const extractClickInfo = () => {
        const nodeToUrlMap: Record<string, string> = {};
        
        // 正则表达式匹配click语句
        const clickRegex = /click\s+(\w+)\s+["']?(https?:\/\/[^"'\s]+)["']?/g;
        let match;
        
        // 查找所有匹配项
        while ((match = clickRegex.exec(chart)) !== null) {
          if (match.length >= 3) {
            const nodeName = match[1];
            const url = match[2];
            if (nodeName && url) {
              nodeToUrlMap[nodeName] = url;
              console.log(`找到节点 ${nodeName} 的URL: ${url}`);
            }
          }
        }
        
        return nodeToUrlMap;
      };
      
      // 提取节点到URL的映射
      const nodeUrlMap = extractClickInfo();
      console.log("节点URL映射表:", nodeUrlMap);

      // 处理点击事件
      const handleClick = (event: MouseEvent) => {
        console.log("图表被点击:", event.target);
        
        // 通过遍历DOM树找到带有flowchart-前缀的元素ID
        let currentElement = event.target as Element | null;
        let nodeId = null;
        let nodeName = null;
        
        // 向上遍历找到节点元素
        while (currentElement && currentElement !== containerRef.current) {
          if (currentElement.id && currentElement.id.startsWith('flowchart-')) {
            nodeId = currentElement.id;
            // 从ID中提取节点名称 (格式通常是 flowchart-NodeName-123)
            nodeName = nodeId.replace('flowchart-', '').split('-')[0];
            console.log("找到节点:", nodeName);
            break;
          }
          currentElement = currentElement.parentElement;
        }
        
        // 如果找到节点名称，并且在映射表中有对应的URL
        if (nodeName && typeof nodeName === 'string' && nodeName in nodeUrlMap) {
          const url = nodeUrlMap[nodeName];
          if (url) {
            console.log("找到URL:", url);
            
            // 阻止默认行为
            event.preventDefault();
            event.stopPropagation();
            
            // 处理不同类型的GitHub链接
            if (url.includes('github.com')) {
              if (url.includes('/blob/')) {
                // 文件链接
                console.log("打开文件查看器");
                setSelectedFileUrl(url);
                setIsCodeViewerOpen(true);
              } else if (url.includes('/tree/')) {
                // 目录链接
                console.log("打开目录查看器");
                setSelectedDirUrl(url);
                setIsDirViewerOpen(true);
              } else {
                // 其他GitHub链接
                console.log("打开其他GitHub链接");
                window.open(url, '_blank');
              }
            } else {
              // 非GitHub链接
              console.log("打开外部链接");
              window.open(url, '_blank');
            }
          }
        } else {
          console.log("未找到对应的URL");
        }
      };

      mermaid.contentLoaded();
      
      // Wait for the SVG to be rendered
      setTimeout(() => {
        void initializePanZoom();
        
        // 为图表容器添加点击事件监听
        if (containerRef.current) {
          // 先移除可能存在的旧监听器
          containerRef.current.removeEventListener('click', handleClick as unknown as EventListener);
          // 添加新的监听器
          containerRef.current.addEventListener('click', handleClick as unknown as EventListener);
          console.log("已添加点击事件监听器");
        }
      }, 100);

      // 清理函数
      return () => {
        if (containerRef.current) {
          containerRef.current.removeEventListener('click', handleClick as unknown as EventListener);
          console.log("已移除点击事件监听器");
        }
      };
    } catch (error) {
      console.error("Mermaid syntax validation: FAILED ❌");
      console.error("Error details:", error);
      setRenderError(`Mermaid 语法错误: ${error instanceof Error ? error.message : String(error)}`);
      
      return () => {
        // 无需清理
      };
    }
  }, [chart, zoomingEnabled]); // Added zoomingEnabled to dependencies

  if (renderError) {
    return (
      <div className="mx-auto max-w-2xl rounded border-2 border-red-500 bg-red-50 p-4 text-red-700">
        <h3 className="mb-2 font-bold">图表渲染错误</h3>
        <p className="mb-4">{renderError}</p>
        <details className="mt-4">
          <summary className="cursor-pointer font-semibold">查看 Mermaid 代码</summary>
          <pre className="mt-2 max-h-80 overflow-auto whitespace-pre-wrap rounded bg-gray-100 p-4 text-sm">{chart}</pre>
        </details>
      </div>
    );
  }

  return (
    <>
      <div
        ref={containerRef}
        className="w-full max-w-full overflow-visible p-4"
      >
        <div
          key={`${chart}-${zoomingEnabled}`}
          className="mermaid w-full min-h-[400px]"
        >
          {chart}
        </div>
      </div>
      
      {/* 代码查看器对话框 */}
      <Dialog open={isCodeViewerOpen} onOpenChange={setIsCodeViewerOpen}>
        <DialogContent className="max-w-4xl h-[80vh] p-0">
          <DialogTitle className="sr-only">查看代码</DialogTitle>
          {selectedFileUrl && (
            <CodeViewer 
              fileUrl={selectedFileUrl} 
              onClose={() => setIsCodeViewerOpen(false)}
              repoUrl={repoUrl}
            />
          )}
        </DialogContent>
      </Dialog>

      {/* 目录查看器对话框 */}
      <Dialog open={isDirViewerOpen} onOpenChange={setIsDirViewerOpen}>
        <DialogContent className="max-w-4xl h-[80vh] p-0">
          <DialogTitle className="sr-only">浏览目录</DialogTitle>
          {selectedDirUrl && (
            <DirectoryViewer 
              dirUrl={selectedDirUrl} 
              onClose={() => setIsDirViewerOpen(false)}
              repoUrl={repoUrl}
            />
          )}
        </DialogContent>
      </Dialog>
    </>
  );
};

export default MermaidChart;
